<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { recipeApi } from '../request'
import type { Recipe } from '../request/api/recipe'

const router = useRouter()

// 表单数据
const recipeForm = ref<Omit<Recipe, 'id' | 'createdAt'>>({
  name: '',
  ingredients: [''],
  steps: [''],
  type: 'meat',
  mealTypes: ['dinner'],
  spicyLevel: 0,
  cookingTime: 30,
  tags: [''],
  imageUrl: ''
})

// 文件上传相关
const imageFile = ref<File | null>(null)
const imagePreview = ref('')
const uploadError = ref('')
const isUploading = ref(false)
const dropZone = ref<HTMLDivElement | null>(null)

// 处理图片选择
const handleImageSelect = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    handleFile(input.files[0])
  }
}

// 处理文件
const handleFile = (file: File) => {
  // 验证文件类型
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
    uploadError.value = '只支持 JPG、PNG 和 GIF 格式的图片'
    return
  }
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    uploadError.value = '图片大小不能超过 5MB'
    return
  }

  imageFile.value = file
  uploadError.value = ''
  
  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target?.result as string
  }
  reader.readAsDataURL(file)
}

// 处理拖拽事件
const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  if (dropZone.value) {
    dropZone.value.classList.add('border-primary-500')
  }
}

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault()
  if (dropZone.value) {
    dropZone.value.classList.remove('border-primary-500')
  }
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  if (dropZone.value) {
    dropZone.value.classList.remove('border-primary-500')
  }
  
  const files = event.dataTransfer?.files
  if (files && files[0]) {
    handleFile(files[0])
  }
}

// 动态添加输入框
const addIngredient = () => {
  recipeForm.value.ingredients.push('')
}

const addStep = () => {
  recipeForm.value.steps.push('')
}

const addTag = () => {
  recipeForm.value.tags.push('')
}

// 移除输入框
const removeIngredient = (index: number) => {
  recipeForm.value.ingredients.splice(index, 1)
}

const removeStep = (index: number) => {
  recipeForm.value.steps.splice(index, 1)
}

const removeTag = (index: number) => {
  recipeForm.value.tags.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  try {
    isUploading.value = true
    
    // 如果有图片，先上传图片
    if (imageFile.value) {
      const response = await recipeApi.uploadImage(imageFile.value)
      recipeForm.value.imageUrl = response.imageUrl
    }
    
    // 创建菜谱
    await recipeApi.createRecipe({
      ...recipeForm.value,
      ingredients: recipeForm.value.ingredients.filter(i => i.trim() !== ''),
      steps: recipeForm.value.steps.filter(s => s.trim() !== ''),
      tags: recipeForm.value.tags.filter(t => t.trim() !== '')
    })
    
    // 创建成功，跳转到首页
    router.push('/')
  } catch (error) {
    console.error('创建菜谱失败:', error)
    uploadError.value = '创建菜谱失败，请重试'
  } finally {
    isUploading.value = false
  }
}
</script>

<template>
  <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="card">
      <div class="p-6">
        <h1 class="text-3xl font-bold text-gray-900 mb-8">创建新菜谱</h1>
        
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 基本信息 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">菜品名称</label>
            <input
              v-model="recipeForm.name"
              type="text"
              required
              class="input"
              placeholder="请输入菜品名称"
            />
          </div>

          <!-- 图片上传 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">菜品图片</label>
            <div
              ref="dropZone"
              class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg transition-colors duration-200 cursor-pointer hover:border-primary-500"
              @dragover="handleDragOver"
              @dragleave="handleDragLeave"
              @drop="handleDrop"
            >
              <div class="space-y-1 text-center">
                <div v-if="imagePreview" class="mb-4">
                  <img :src="imagePreview" alt="预览" class="mx-auto h-32 w-auto" />
                </div>
                <div class="flex text-sm text-gray-600">
                  <label class="relative cursor-pointer bg-white rounded-md font-medium text-primary-600 hover:text-primary-500">
                    <span>上传图片</span>
                    <input
                      type="file"
                      class="sr-only"
                      accept="image/jpeg,image/png,image/gif"
                      @change="handleImageSelect"
                    />
                  </label>
                  <p class="pl-1">或拖放图片到此处</p>
                </div>
                <p class="text-xs text-gray-500">PNG, JPG, GIF 格式，最大 5MB</p>
                <p v-if="uploadError" class="text-red-500 text-sm mt-2">{{ uploadError }}</p>
              </div>
            </div>
          </div>

          <!-- 类型和时间 -->
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">菜品类型</label>
              <select v-model="recipeForm.type" class="input">
                <option value="meat">荤菜</option>
                <option value="vegetable">素菜</option>
                <option value="soup">汤类</option>
              </select>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">用餐时间</label>
              <div class="flex flex-wrap gap-2">
                <label
                  v-for="type in ['breakfast', 'lunch', 'dinner']"
                  :key="type"
                  class="inline-flex items-center px-3 py-2 rounded-lg border cursor-pointer transition-colors duration-200"
                  :class="[
                    recipeForm.mealTypes.includes(type)
                      ? 'bg-primary-100 border-primary-500 text-primary-700'
                      : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50'
                  ]"
                >
                  <input
                    type="checkbox"
                    :value="type"
                    v-model="recipeForm.mealTypes"
                    class="sr-only"
                  />
                  <span class="text-sm font-medium">
                    {{ type === 'breakfast' ? '早餐' : type === 'lunch' ? '午餐' : '晚餐' }}
                  </span>
                </label>
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">烹饪时间（分钟）</label>
              <input
                v-model.number="recipeForm.cookingTime"
                type="number"
                min="1"
                required
                class="input"
              />
            </div>
          </div>

          <!-- 辣度 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">辣度</label>
            <input
              v-model.number="recipeForm.spicyLevel"
              type="range"
              min="0"
              max="5"
              class="w-full"
            />
            <div class="flex justify-between text-xs text-gray-500">
              <span>不辣</span>
              <span>微辣</span>
              <span>中辣</span>
              <span>特辣</span>
              <span>超辣</span>
              <span>地狱辣</span>
            </div>
          </div>

          <!-- 食材 -->
          <div>
            <div class="flex justify-between items-center mb-2">
              <label class="block text-sm font-medium text-gray-700">食材</label>
              <button
                type="button"
                @click="addIngredient"
                class="text-sm text-primary-600 hover:text-primary-500"
              >
                添加食材
              </button>
            </div>
            <div class="space-y-2">
              <div
                v-for="(ingredient, index) in recipeForm.ingredients"
                :key="index"
                class="flex gap-2"
              >
                <input
                  v-model="recipeForm.ingredients[index]"
                  type="text"
                  required
                  class="input"
                  placeholder="例如：五花肉 500g"
                />
                <button
                  type="button"
                  @click="removeIngredient(index)"
                  class="text-red-500 hover:text-red-600"
                >
                  删除
                </button>
              </div>
            </div>
          </div>

          <!-- 步骤 -->
          <div>
            <div class="flex justify-between items-center mb-2">
              <label class="block text-sm font-medium text-gray-700">烹饪步骤</label>
              <button
                type="button"
                @click="addStep"
                class="text-sm text-primary-600 hover:text-primary-500"
              >
                添加步骤
              </button>
            </div>
            <div class="space-y-2">
              <div
                v-for="(step, index) in recipeForm.steps"
                :key="index"
                class="flex gap-2"
              >
                <div class="flex-shrink-0 w-8 h-8 flex items-center justify-center rounded-full bg-primary-100 text-primary-600 font-medium">
                  {{ index + 1 }}
                </div>
                <input
                  v-model="recipeForm.steps[index]"
                  type="text"
                  required
                  class="input"
                  placeholder="描述这个步骤..."
                />
                <button
                  type="button"
                  @click="removeStep(index)"
                  class="text-red-500 hover:text-red-600"
                >
                  删除
                </button>
              </div>
            </div>
          </div>

          <!-- 标签 -->
          <div>
            <div class="flex justify-between items-center mb-2">
              <label class="block text-sm font-medium text-gray-700">标签</label>
              <button
                type="button"
                @click="addTag"
                class="text-sm text-primary-600 hover:text-primary-500"
              >
                添加标签
              </button>
            </div>
            <div class="flex flex-wrap gap-2">
              <div
                v-for="(tag, index) in recipeForm.tags"
                :key="index"
                class="flex items-center"
              >
                <input
                  v-model="recipeForm.tags[index]"
                  type="text"
                  class="input"
                  placeholder="例如：家常菜"
                />
                <button
                  type="button"
                  @click="removeTag(index)"
                  class="text-red-500 hover:text-red-600"
                >
                  删除
                </button>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end">
            <button
              type="submit"
              class="btn btn-primary"
              :disabled="isUploading"
            >
              {{ isUploading ? '创建中...' : '创建菜谱' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>